﻿namespace MDXStudio
{
    using Microsoft.AnalysisServices.AdomdClient;
    using System;
    using System.ComponentModel;
    using System.Windows.Forms;

    internal class VirtualGrid
    {
        private readonly Context AxesContext;
        internal string CellProperty;
        internal CellSet CellSetBinding;
        private int colCount;
        private int colDepth;
        private readonly DataGridView DisplayGrid;
        private bool m_fRowsIncludeHierarchyName;
        private bool m_fShowFormattedValue;
        private readonly ContextMenuStrip mContextMenu;
        private int rowCount;
        private int rowCountCurrent;
        private int rowDepth;

        public VirtualGrid(DataGridView GridControl, Context in_AxesContext)
        {
            this.DisplayGrid = GridControl;
            this.AxesContext = in_AxesContext;
            this.mContextMenu = this.BuildContextMenu();
            this.DisplayGrid.ContextMenuStrip = this.mContextMenu;
        }

        private ContextMenuStrip BuildContextMenu()
        {
            ContextMenuStrip strip = new ContextMenuStrip();
            ToolStripMenuItem item = new ToolStripMenuItem("Coordinates", null, new EventHandler(this.OnContextMenuClick), "mItemCoordinates");
            strip.Items.Add(item);
            item = new ToolStripMenuItem("Clear watches", null, new EventHandler(this.OnContextMenuClick), "mItemClearWatches");
            strip.Items.Add(item);
            item = new ToolStripMenuItem("Debug", null, new EventHandler(this.OnContextMenuClick), "mItemDebug");
            strip.Items.Add(item);
            item = new ToolStripMenuItem("Show Calculation", null, new EventHandler(this.OnContextMenuClick), "mItemShowCalculation");
            strip.Items.Add(item);
            strip.Opening += new CancelEventHandler(this.mContextMenuResultGrid_Opening);
            return strip;
        }

        public void CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((e.ColumnIndex < (this.colCount + this.rowDepth)) && (e.RowIndex < (this.rowCount + this.colDepth)))
            {
                if ((e.ColumnIndex < this.rowDepth) && (e.RowIndex >= this.colDepth))
                {
                    Member member = this.CellSetBinding.Axes[1].Positions[e.RowIndex - this.colDepth].Members[e.ColumnIndex];
                    this.ShowMemberProperties(member);
                }
                else if ((e.ColumnIndex >= this.rowDepth) && (e.RowIndex < this.colDepth))
                {
                    int num = e.ColumnIndex - this.rowDepth;
                    bool flag = true;
                    if (this.m_fRowsIncludeHierarchyName)
                    {
                        if ((num % 2) == 0)
                        {
                            flag = false;
                        }
                        num /= 2;
                    }
                    if (flag)
                    {
                        Member member2 = this.CellSetBinding.Axes[0].Positions[num].Members[e.RowIndex];
                        this.ShowMemberProperties(member2);
                    }
                }
                else if ((e.ColumnIndex >= this.rowDepth) && (e.RowIndex >= this.colDepth))
                {
                    int num2 = ((e.RowIndex - this.colDepth) * this.colCount) + (e.ColumnIndex - this.rowDepth);
                    Cell cl = this.CellSetBinding.Cells[num2];
                    this.ShowCellProperties(cl);
                }
            }
        }

        public void CellEnter(object sender, DataGridViewCellEventArgs e, AdomdConnection Connection, string cube)
        {
            if ((e.ColumnIndex < (this.colCount + this.rowDepth)) && (e.RowIndex < (this.rowCount + this.colDepth)))
            {
                this.AxesContext.Clear();
                if ((e.ColumnIndex >= this.rowDepth) && (e.RowIndex < this.colDepth))
                {
                    int num = e.ColumnIndex - this.rowDepth;
                    bool flag = true;
                    if (this.m_fRowsIncludeHierarchyName)
                    {
                        if ((num % 2) == 0)
                        {
                            flag = false;
                        }
                        num /= 2;
                    }
                    if (flag)
                    {
                        this.AxesContext.StartContext(Connection, cube);
                        this.AxesContext.UpdateCoordinates(this.CellSetBinding.Axes[0].Positions[num], this.CellSetBinding.OlapInfo.AxesInfo.Axes[0]);
                    }
                }
                else if ((e.ColumnIndex < this.rowDepth) && (e.RowIndex >= this.colDepth))
                {
                    this.AxesContext.StartContext(Connection, cube);
                    this.AxesContext.UpdateCoordinates(this.CellSetBinding.Axes[1].Positions[e.RowIndex - this.colDepth], this.CellSetBinding.OlapInfo.AxesInfo.Axes[1]);
                }
                else if ((e.ColumnIndex >= this.rowDepth) && (e.RowIndex >= this.colDepth))
                {
                    int num2 = e.RowIndex - this.colDepth;
                    int num3 = e.ColumnIndex - this.rowDepth;
                    this.AxesContext.StartContext(Connection, cube);
                    if (this.CellSetBinding.Axes.Count > 0)
                    {
                        this.AxesContext.UpdateCoordinates(this.CellSetBinding.Axes[0].Positions[num3], this.CellSetBinding.OlapInfo.AxesInfo.Axes[0]);
                    }
                    if (this.CellSetBinding.Axes.Count > 1)
                    {
                        this.AxesContext.UpdateCoordinates(this.CellSetBinding.Axes[1].Positions[num2], this.CellSetBinding.OlapInfo.AxesInfo.Axes[1]);
                    }
                }
            }
        }

        public void CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
        {
            if ((e.ColumnIndex < (this.colCount + this.rowDepth)) && (e.RowIndex < (this.rowCount + this.colDepth)))
            {
                if ((e.ColumnIndex < this.rowDepth) && (e.RowIndex >= this.colDepth))
                {
                    Member member = this.CellSetBinding.Axes[1].Positions[e.RowIndex - this.colDepth].Members[e.ColumnIndex];
                    e.Value = member.Caption;
                }
                if ((e.ColumnIndex >= this.rowDepth) && (e.RowIndex < this.colDepth))
                {
                    int num = e.ColumnIndex - this.rowDepth;
                    bool flag = true;
                    if (this.m_fRowsIncludeHierarchyName)
                    {
                        if ((num % 2) == 0)
                        {
                            flag = false;
                        }
                        num /= 2;
                    }
                    if (flag)
                    {
                        Member member2 = this.CellSetBinding.Axes[0].Positions[num].Members[e.RowIndex];
                        e.Value = member2.Caption;
                    }
                    else
                    {
                        e.Value = this.CellSetBinding.OlapInfo.AxesInfo.Axes[0].Hierarchies[e.RowIndex].Name;
                    }
                }
                if ((e.ColumnIndex >= this.rowDepth) && (e.RowIndex >= this.colDepth))
                {
                    int num2 = ((e.RowIndex - this.colDepth) * this.colCount) + (e.ColumnIndex - this.rowDepth);
                    Cell cell = this.CellSetBinding.Cells[num2];
                    try
                    {
                        if (this.CellProperty == null)
                        {
                            if (this.m_fShowFormattedValue)
                            {
                                e.Value = cell.FormattedValue;
                            }
                            else
                            {
                                e.Value = cell.Value;
                            }
                        }
                        else
                        {
                            e.Value = cell.CellProperties[this.CellProperty].Value;
                        }
                    }
                    catch (Exception exception)
                    {
                        e.Value = "#Error";
                        DataGridViewCell cell2 = this.DisplayGrid.Rows[e.RowIndex].Cells[e.ColumnIndex];
                        cell2.ToolTipText = exception.Message;
                    }
                }
            }
        }

        public void DrawCellSetInGrid(CellSet csResult, MessageLog MessageLog, bool fRowsIncludeHierarchyName)
        {
            try
            {
                this.DisplayGrid.SuspendLayout();
                this.DisplayGrid.Columns.Clear();
                this.DisplayGrid.Rows.Clear();
                this.CellSetBinding = csResult;
                this.m_fShowFormattedValue = null != this.CellSetBinding.OlapInfo.CellInfo.CellProperties.Find("FORMATTED_VALUE");
                this.m_fRowsIncludeHierarchyName = fRowsIncludeHierarchyName;
                if (csResult.Axes.Count > 2)
                {
                    MessageLog.WriteErrorMessage("Too many axes in the result.");
                }
                else if (csResult.Axes.Count == 0)
                {
                    MessageLog.WriteMessage("Query result is empty.");
                }
                else
                {
                    this.colCount = csResult.Axes[0].Positions.Count;
                    this.colDepth = 0;
                    if (!this.DisplayGrid.ColumnHeadersVisible)
                    {
                        this.colDepth = csResult.OlapInfo.AxesInfo.Axes[0].Hierarchies.Count;
                    }
                    this.rowCount = 0;
                    this.rowDepth = 0;
                    if (csResult.Axes.Count > 1)
                    {
                        this.rowCount = csResult.Axes[1].Positions.Count;
                        this.rowDepth = csResult.OlapInfo.AxesInfo.Axes[1].Hierarchies.Count;
                    }
                    else
                    {
                        this.rowCount = 1;
                        this.rowDepth = 0;
                    }
                    for (int i = 0; i < this.rowDepth; i++)
                    {
                        this.DisplayGrid.Columns.Add("rowColumn" + (i + 1), csResult.OlapInfo.AxesInfo.Axes[1].Hierarchies[i].Name);
                        this.DisplayGrid.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                    }
                    for (int j = 0; j < this.colCount; j++)
                    {
                        if (fRowsIncludeHierarchyName)
                        {
                            this.DisplayGrid.Columns.Add("columnHierarchy" + (j + 1), "");
                            this.DisplayGrid.Columns[this.rowDepth + j].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        }
                        if (this.DisplayGrid.Columns.Count > 0)
                        {
                            DataGridViewColumn dataGridViewColumn = new DataGridViewColumn();
                            dataGridViewColumn.FillWeight = 1f;
                            if (this.DisplayGrid.ColumnHeadersVisible)
                            {
                                dataGridViewColumn.Name = csResult.Axes[0].Positions[j].Members[0].Caption;
                            }
                            else
                            {
                                dataGridViewColumn.Name = ".";
                            }
                            dataGridViewColumn.CellTemplate = this.DisplayGrid.Columns[0].CellTemplate;
                            this.DisplayGrid.Columns.Add(dataGridViewColumn);
                        }
                        else
                        {
                            this.DisplayGrid.Columns.Add(".", csResult.Axes[0].Positions[j].Members[0].Caption);
                        }
                        this.DisplayGrid.Columns[this.rowDepth + j].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                    }
                    this.rowCountCurrent = this.rowCount;
                    this.DisplayGrid.RowCount = this.colDepth + this.rowCountCurrent;
                    for (int k = 0; k < this.colDepth; k++)
                    {
                        string caption = null;
                        for (int m = 0; m < this.colCount; m++)
                        {
                            int num5 = fRowsIncludeHierarchyName ? 1 : 0;
                            DataGridViewCell cell = this.DisplayGrid.Rows[k].Cells[(this.rowDepth + m) + num5];
                            Member member = csResult.Axes[0].Positions[m].Members[k];
                            if (member.Caption != caption)
                            {
                                cell.Value = member.Caption;
                                caption = member.Caption;
                            }
                            if (fRowsIncludeHierarchyName)
                            {
                                cell = this.DisplayGrid.Rows[k].Cells[this.rowDepth + m];
                                cell.Value = csResult.OlapInfo.AxesInfo.Axes[0].Hierarchies[k].Name;
                            }
                        }
                    }
                    if (fRowsIncludeHierarchyName)
                    {
                        this.colCount *= 2;
                    }
                    if (!fRowsIncludeHierarchyName)
                    {
                        MessageLog.WriteMessage(string.Concat(new object[] { "Displaying ", this.colCount, " columns and ", this.rowCount, " rows." }));
                    }
                }
            }
            finally
            {
                this.DisplayGrid.AutoResizeColumns();
                this.DisplayGrid.ResumeLayout();
            }
        }

        private eArea GetArea(int pColIndex, int pRowIndex)
        {
            if (((pColIndex >= this.rowDepth) && (pColIndex < (this.rowDepth + this.colCount))) && ((pRowIndex >= this.colDepth) && (pRowIndex < (this.colDepth + this.rowCount))))
            {
                return eArea.Cells;
            }
            if (((pColIndex >= this.rowDepth) && (pColIndex < (this.rowDepth + this.colCount))) && (pRowIndex < this.colDepth))
            {
                return eArea.Cols;
            }
            if (((pColIndex < this.rowDepth) && (pRowIndex >= this.colDepth)) && (pRowIndex < (this.colDepth + this.rowCount)))
            {
                return eArea.Rows;
            }
            return eArea.None;
        }

        private void mContextMenuResultGrid_Opening(object sender, CancelEventArgs e)
        {
            foreach (ToolStripMenuItem item in this.mContextMenu.Items)
            {
                item.Visible = false;
            }
            DataGridViewCell currentCell = this.DisplayGrid.CurrentCell;
            if (currentCell != null)
            {
                switch (this.GetArea(currentCell.ColumnIndex, currentCell.RowIndex))
                {
                    case eArea.None:
                        e.Cancel = true;
                        return;

                    case eArea.Rows:
                    case eArea.Cols:
                        this.mContextMenu.Items["mItemClearWatches"].Visible = true;
                        return;

                    case eArea.Cells:
                        e.Cancel = true;
                        return;
                }
            }
        }

        private void OnContextMenuClick(object sender, EventArgs e)
        {
            string name = ((ToolStripMenuItem) sender).Name;
            if (name != null)
            {
                if (!(name == "mItemClearWatches"))
                {
                    if ((name == "mItemDebug") || (name == "mItemShowCalculation"))
                    {
                    }
                }
                else
                {
                    Program.m_MainForm.ClearDebugWatch();
                }
            }
        }

        public void Redraw()
        {
            this.DisplayGrid.Invalidate();
        }

        public void Scroll(ScrollEventArgs e)
        {
            if (((this.rowCountCurrent < this.rowCount) && (e.ScrollOrientation == ScrollOrientation.VerticalScroll)) && (e.NewValue > e.OldValue))
            {
                int rowCount = e.NewValue + 0x100;
                if (rowCount > this.rowCount)
                {
                    rowCount = this.rowCount;
                }
                if (rowCount > this.rowCountCurrent)
                {
                    this.DisplayGrid.RowCount += rowCount - this.rowCountCurrent;
                    this.rowCountCurrent = rowCount;
                }
            }
        }

        public void SetContextMenu()
        {
            DataGridViewCell currentCell = this.DisplayGrid.CurrentCell;
        }

        private void ShowCellProperties(Cell cl)
        {
            CellPropertiesWindow window = new CellPropertiesWindow();
            CellPropertyCollection.Enumerator enumerator = cl.CellProperties.GetEnumerator();
            while (enumerator.MoveNext())
            {
                Microsoft.AnalysisServices.AdomdClient.CellProperty current = enumerator.Current;
                string message = null;
                try
                {
                    message = Convert.ToString(current.Value);
                }
                catch (Exception exception)
                {
                    message = exception.Message;
                }
                window.AddProperty(current.Name, message);
            }
            window.Show();
        }

        private void ShowMemberProperties(Member member)
        {
            CellPropertiesWindow window = new CellPropertiesWindow();
            window.Text = "Member Properties";
            window.AddProperty("Caption", member.Caption);
            window.AddProperty("Name", member.Name);
            window.AddProperty("Unique Name", member.UniqueName);
            window.AddProperty("Level Name", member.LevelName);
            window.AddProperty("Level Depth", member.LevelDepth.ToString());
            window.AddProperty("Children Count", member.ChildCount.ToString());
            if (member.Parent != null)
            {
                window.AddProperty("Parent Caption", member.Parent.Caption);
                window.AddProperty("Parent Unique Name", member.Parent.UniqueName);
            }
            window.AddProperty("Drilled Down", member.DrilledDown.ToString());
            window.AddProperty("Parent Same as Previous", member.ParentSameAsPrevious.ToString());
            MemberPropertyCollection.Enumerator enumerator = member.MemberProperties.GetEnumerator();
            while (enumerator.MoveNext())
            {
                MemberProperty current = enumerator.Current;
                string message = null;
                try
                {
                    message = Convert.ToString(current.Value);
                }
                catch (Exception exception)
                {
                    message = exception.Message;
                }
                window.AddProperty(current.Name, message);
            }
            window.Show();
        }

        private enum eArea
        {
            None,
            Rows,
            Cols,
            Cells
        }
    }
}

